import {
  Injectable,
  NestMiddleware,
  Param,
  Get,
  Query,
  Req,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';
import { defaultConfig } from '@game/config/config';
import { ReqUtils } from '@common/utils/req.utils';
import QueryString, { ParsedQs } from 'qs';
import { JwtService } from '@nestjs/jwt';
import { routes } from './routes';
import { flatRoutes } from '@common/utils';
const AUTH_HEADER = 'authorization';

@Injectable()
export class JwtMiddleware implements NestMiddleware {
  constructor(private jwtService: JwtService) {}
  async use(req: Request, res: Response, next: NextFunction) {
    /**
     *  从路由配置里哪对应的字段 后面做rbac也是存一个缓存 尽量不读数据库
     */
    // 先解析当前的路由控制 再去routes里匹配

    const urls = req.url?.split('/');
    // 考虑到动态路由的问题
    const module = urls[1];
    const controller = urls[2];
    const methond = urls[3];
    //...参数

    const isTokenAuth = flatRoutes(
      routes,
      '/' + module + '/' + controller,
      methond,
    );

    if (isTokenAuth) {
      // 参数校验
      const token = req.headers['authorization']?.split(' ')[1];

      if (!token) {
        if (defaultConfig.NODE_ENV == 'dev') {
          let data = {};
          if (req.method.toUpperCase() == 'GET') {
            data = req.query;
          } else if (req.method.toUpperCase() == 'POST') {
            data = req.body;
          }
          req.user = data;
          next();
          return;
        }
        throw new HttpException('无权限访问', HttpStatus.UNAUTHORIZED);
      }

      try {
        // 解算
        const decoded = this.jwtService.verify(token);
        req.user = decoded;
      } catch (error) {
        throw new HttpException('鉴权失败', HttpStatus.UNAUTHORIZED);
      }
    }

    next();
  }
}
